package com;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

public class ConsumerTest {
	
	@Test
	public void topicConsumer() throws JMSException
	{
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		Connection conn = factory.createConnection();
		conn.start();
		
		Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
		Topic topic = session.createTopic("topic_xx001");
		MessageConsumer consumer = session.createConsumer(topic);
		TextMessage message = (TextMessage)consumer.receive();
		message.acknowledge();
		
		System.out.println(message.getText());
		
		
		conn.stop();
		conn.close();
	}
	@Test
	public void asynConsumer() throws JMSException
	{
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		Connection conn = factory.createConnection();
		conn.start();
		
		Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
		Queue queue = session.createQueue("xx002");
		MessageConsumer consumer = session.createConsumer(queue);
		consumer.setMessageListener(new MessageListener() {
			
			@Override
			public void onMessage(Message arg0) {
				// TODO Auto-generated method stub
				TextMessage msg = (TextMessage)arg0;
				try {
					System.out.println(msg.getText());
					msg.acknowledge();
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		
	}
	
	
	public static void main(String[] args) throws JMSException {
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		Connection conn = factory.createConnection();
		conn.start();
		
		Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
		Queue queue = session.createQueue("xx001");
		
		MessageConsumer consumer = session.createConsumer(queue);
		TextMessage msg1 = (TextMessage)consumer.receive();
		System.out.println(msg1.getText());
		TextMessage msg2 = (TextMessage)consumer.receive();
		System.out.println(msg2.getText());
		msg2.acknowledge();
		
		
		conn.stop();
		conn.close();
		System.out.println("end.....!");
	}
}
